import React, { useContext, useEffect, useState } from "react";
import AnomalyCard from "../AnomalyCard";
import styles from "./index.module.less";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";
import ChartPointModal from "./components/ChartPointModal";
import { ANOMALY_NAME_TYPE_MAP, ANOMALY_TYPE_MAP } from "@/pages/BigScreen/constants";
import { fetchPredictedValueList } from "@/pages/BigScreen/context/services/anomaly";
import { message } from "@supcon/supcon-5t-design";
import { getPosition } from "@/utils/position";

// 定义位置接口
export interface MarkerPosition {
  x: number; // x坐标的百分比值
  y: number; // y坐标的百分比值
}

export interface AnomalyItem {
  id: string;
  evaluationItemId?: string;
  type: "red" | "yellow" | "green" | "gray";
  code: string;
  name: string;
  location: string;
  bottomTagResps: any[];
  description: string;
  updateTime: string;
  value?: number; // 实时值
  visible?: boolean; // 是否显示
  position?: MarkerPosition; // 添加位置信息，用于在地图上标记
  // 添加额外可选字段，来自 evaluationItems
  groupType?: number; // 评估组类型
  currentState?: number; // 当前状态
  realValue?: number; // 实时值
  importance?: number; // 重要程度
  tagUnit?: string; // 位号单位
  isShelve?: boolean; // 是否搁置
  isOpen?: boolean; // 是否搁置
  evaluationItemName?: string; // 评估项名称，用于分组
  // 添加图表数据字段
  chartData?: any; // 用于存储图表数据
  tagDesc?: string; // 项目名称
  abnormalCause?: string; // 异常原因
  predictTime?: string; // 预测时间
}

interface AnomalyListProps {
  anomalies: AnomalyItem[];
  onItemClick?: (item: AnomalyItem) => void;
  selectedAnomaly?: AnomalyItem | null;
  onItemIconClick?: (item: AnomalyItem, e?: any) => void;
}

const AnomalyList: React.FC<AnomalyListProps> = ({
  anomalies,
  onItemClick,
  selectedAnomaly,
  onItemIconClick,
}) => {
  const bigScreenContext = useContext(BigScreenContext);
  const { setChartFull, chatRef } = bigScreenContext;

  // 添加状态来控制图表模态框
  const [chartModalVisible, setChartModalVisible] = useState<boolean>(false);
  const [currentGroupChart, setCurrentGroupChart] = useState<{
    title: string;
    type: "red" | "yellow" | "green" | "gray";
    chartData: any;
    codeOptions: string[]; // 添加codeOptions字段
  }>({
    title: "",
    type: "green",
    chartData: null,
    codeOptions: [], // 初始化为空数组
  });

  // 按evaluationItemName分组
  const groupedAnomalies = React.useMemo(() => {
    const grouped: Record<string, AnomalyItem[]> = {};
    console.log("anomalies", anomalies);
    anomalies.forEach(item => {
      const groupName = item.name || '未分类';
      if (!grouped[groupName]) {
        grouped[groupName] = [];
      }
      if (item.bottomTagResps && Array.isArray(item.bottomTagResps)) {
        const mappedItems = item.bottomTagResps.map(res => {
          console.log("res", res);
          return {
            ...res,
            id: res.id,
            evaluationItemId: item.id,
            evaluationItemName: item.name,
            groupType: item.groupType,
            name: res.tagDesc,
            code: res.tagName,
            location: ANOMALY_NAME_TYPE_MAP?.[Number(JSON.parse(res?.ext || "{}")?.status_now)] || "正常",
            type: ANOMALY_TYPE_MAP?.[Number(JSON.parse(res?.ext || "{}")?.status_now)] || "green",
            description: res.tagReason,
            position: getPosition(res.tagDesc, item.groupType),
            updateTime: res.updateTime,
            predictTime: null,
            isShelve: res.isOpen,
            value: Number(JSON.parse(res?.ext || "{}")?.tag_value),
          };
        });
        console.log("mappedItems", mappedItems);
        grouped[groupName].push(...mappedItems);
      }
    });

    return grouped;
  }, [anomalies]);
  console.log("groupedAnomalies", groupedAnomalies);
  // 获取分组名称列表
  const groupNames = Object.keys(groupedAnomalies);

  // 用于跟踪每个分组的折叠状态，默认都是展开的
  const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>({});

  // 处理分组点击事件
  const handleGroupHeaderClick = (groupName: string) => {
    setCollapsedGroups(prev => ({
      ...prev,
      [groupName]: !prev[groupName]
    }));
  };

  const handleChatClick = (groupName: string, e: React.MouseEvent) => {
    // 阻止事件冒泡，防止触发父元素的onClick事件
    e.stopPropagation();

    // 默认选中第一个卡片
    onItemClick && onItemClick(groupedAnomalies?.[groupName]?.[0] ?? {})

    chatRef?.current?.handleChat(`查看${groupName}报警详细信息`)
  }

  const processAnomalyTrendData = (data: any) => {
    const timeEntries = Object.entries(data)
      .sort(([timeA], [timeB]) => new Date(timeA).getTime() - new Date(timeB).getTime());

    // 提取时间和值
    const times = timeEntries.map(([time]) => time);
    const values = timeEntries.map(([_, value]) => parseFloat(value as string));

    return {
      times,
      values,
    }
  };

  // 处理图表图标点击事件
  const handleChartClick = async (groupName: string, e: React.MouseEvent) => {
    // 阻止事件冒泡
    e.stopPropagation();

    // 收集该分组下所有异常项的数据
    const groupItems = groupedAnomalies[groupName] || [];
    // 提取该组内所有异常项的code
    const codesToShow = groupItems.map(item => item.tagDesc).filter(Boolean);

    // 确定该组的主要类型(优先级：red > yellow > green > gray)
    let groupType: "red" | "yellow" | "green" | "gray" = "gray";
    if (groupItems.some(item => item.type === "red")) {
      groupType = "red";
    } else if (groupItems.some(item => item.type === "yellow")) {
      groupType = "yellow";
    } else if (groupItems.some(item => item.type === "green")) {
      groupType = "green";
    }

    const data = {
      "evaluationItemName": groupName
    }
    const res = await fetchPredictedValueList(data)

    if (res.status) {
      // 处理趋势图数据
      const { content = [] } = res;
      let chartData = content.filter((item) => codesToShow.includes(item?.tagName)).map((item) => {
        let tagTimeAndValueMapping = item?.tagTimeAndValueMapping ?? {};
        let { times, values } = processAnomalyTrendData(tagTimeAndValueMapping)
        return {
          tagName: item?.tagName,
          times,
          values,
          dashedTime: item?.predictTime
        }
      })
      // 设置当前选中组的图表数据
      setCurrentGroupChart({
        title: `${groupName} 异常趋势`,
        type: groupType,
        chartData: chartData,
        codeOptions: codesToShow as any, // 添加code选项
      });
    } else {
      message.error(res.message || '获取异常趋势数据失败')
    }


    // 显示图表模态框
    setChartModalVisible(true);
  }
  useEffect(() => {
    if (chartModalVisible) {
      setChartFull(true);
    } else {
      setChartFull(false);
    }
  }, [chartModalVisible]);

  return (
    <div className={styles["anomaly-list-container"]}>
      {anomalies.length === 0 ? (
        <div className={styles["empty-list"]}>暂无异常数据</div>
      ) : (
        groupNames.map((groupName) => (
          <div key={groupName} className={styles["anomaly-group"]}>
            <div
              className={styles["group-header"]}
              onClick={() => handleGroupHeaderClick(groupName)}
              style={{ cursor: 'pointer' }}
            >
              <div className={styles["group-name"]}>
                <div className={collapsedGroups[groupName] ? styles["triangle-down"] : styles["triangle-up"]}></div>
                {groupName}
              </div>
              <div className={styles["group-count"]}>
                <div
                  className={styles["icon-placeholder-first"]}
                  onClick={(e) => handleChartClick(groupName, e)}
                ></div>
                <div
                  className={styles["icon-placeholder-second"]}
                  onClick={(e) => handleChatClick(groupName, e)}
                ></div>
              </div>
            </div>
            <div
              className={`${styles["anomaly-list"]} ${collapsedGroups[groupName] ? styles["anomaly-list-collapsed"] : ''}`}
            >
              {groupedAnomalies[groupName].map((item) => (
                <AnomalyCard
                  name={item.name}
                  key={item.id}
                  type={item.type}
                  value={item.value}
                  code={item.code}
                  location={item.location}
                  description={item.description}
                  updateTime={item.updateTime}
                  onClick={() => onItemClick && onItemClick(item)}
                  onIconClick={() => onItemIconClick && onItemIconClick(item)}
                  isSelected={selectedAnomaly?.id === item.id}
                  isHold={item.isShelve}
                />
              ))}
            </div>
          </div>
        ))
      )}

      {/* 添加图表模态框组件 */}
      <ChartPointModal
        visible={chartModalVisible}
        title={currentGroupChart.title}
        type={currentGroupChart.type}
        chartData={currentGroupChart.chartData}
        codeOptions={currentGroupChart.codeOptions} // 传递code选项
        onClose={() => setChartModalVisible(false)}
      />
    </div>
  );
};

export default AnomalyList;
